﻿#define _CRT_SECURE_NO_WARNINGS 1

int compare_int(const void* p1, const void* p2)
{
    return *(int*)p1 - *(int*)p2;
}
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
    int* arr = (int*)malloc(sizeof(int) * (nums1Size + nums2Size));
    if (arr == NULL)
    {
        perror("malloc fail");
        exit(1);
    }
    qsort(nums1, nums1Size, sizeof(int), compare_int);
    qsort(nums2, nums2Size, sizeof(int), compare_int);
    int prev = -1;
    int i = 0;
    int n1 = 0, n2 = 0;
    while (n1 < nums1Size && n2 < nums2Size)//不用嵌套两个循环
    {
        if (nums1[n1] == nums2[n2])
        {
            if (nums1[n1] != prev)
                arr[i++] = prev = nums1[n1];
            n1++;
            n2++;
        }
        else if (nums1[n1] > nums2[n2])
        {
            n2++;
        }
        else
        {
            n1++;
        }
    }
    *returnSize = i;
    return arr;
}

